import os.path

import numpy as np
import pandas as pd
from datetime import datetime as datetime_
from tools.framework import get_ui_value
from core.constant import *
from module.static_module.parent.model import AdditionModule


class RevenueCalculateModel(AdditionModule):
    def __init__(self, master):
        super().__init__(master, Module.RevenueCalculate)
        # 实体类映射视图类变量数据
        self.cost_ls = []  # 成本
        self.profit_probability_ls = []  # 盈利概率
        self.profit_cost_multiple_ls = []  # 盈利相对于成本的倍数
        self.loss_cost_multiple_ls = []  # 亏损相对于成本的倍数

        # 映射视图类变量数据默认值
        self.cost = None
        self.profit_probability = None
        self.profit_cost_multiple = None
        self.loss_cost_multiple = None
        # 实体类结构变量
        self.sub_view = None

    def sec_init(self):
        # 实体类映射视图类变量数据
        self.cost_ls = ["1"]
        self.profit_probability_ls = ["0.1,0.9,0.1"]
        self.profit_cost_multiple_ls = ["0.5,10,0.5"]
        self.loss_cost_multiple_ls = ["0.5,10,0.5"]
        from module.addition_module.revenue_calculate.view import RevenueCalculateView
        self.sub_view = RevenueCalculateView(self)

    def get_ui_params(self):
        # 获取ui界面的相关参数
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.Cost)
        self.cost = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.ProfitProbability)
        self.profit_probability = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.ProfitCostMultiple)
        self.profit_cost_multiple = get_ui_value(values, indices, WidgetCategory.Entry)
        values, indices = self.sub_view.auto_layout.get_value(
            LabelMember.LossCostMultiple)
        self.loss_cost_multiple = get_ui_value(values, indices, WidgetCategory.Entry)

    def on_ok(self):
        self.get_ui_params()
        # 获取基本信息
        cost = round(float(self.cost), 4)
        profit_probability_conf_ls = [round(float(x), 4) for x in self.profit_probability.split(',')]
        start = profit_probability_conf_ls[0]
        end = profit_probability_conf_ls[1]
        step = profit_probability_conf_ls[2]
        profit_probability_ls = [round(start + i*step, 4) for i in range(int((end-start) / step + 1))]

        profit_cost_multiple_conf_ls = [float(x) for x in self.profit_cost_multiple.split(',')]
        start = profit_cost_multiple_conf_ls[0]
        end = profit_cost_multiple_conf_ls[1]
        step = profit_cost_multiple_conf_ls[2]
        profit_cost_multiple_ls = [round(start + i*step, 4) for i in range(int((end-start) / step + 1))]

        loss_cost_multiple_conf_ls = [float(x) for x in self.loss_cost_multiple.split(',')]
        start = loss_cost_multiple_conf_ls[0]
        end = loss_cost_multiple_conf_ls[1]
        step = loss_cost_multiple_conf_ls[2]
        loss_cost_multiple_ls = [round(start + i*step, 4) for i in range(int((end-start) / step + 1))]
        # 根据公式生成一张excel表（多sheet）
        # 创建excel空表
        result_path = self.master.file_manager.result_path
        now_time_str = datetime_.now().strftime("%m-%d_%H_%M")
        excel_name = f"revenue_calculate_{now_time_str}.xlsx"
        excel_dir = os.path.join(result_path, "revenue_calculate")
        self.master.file_manager.mk_dir(excel_dir)
        excel_path = os.path.join(excel_dir, excel_name)
        with pd.ExcelWriter(excel_path) as writer:
            for profit_probability in profit_probability_ls:
                info = f"当前测算的盈利概率{profit_probability}"
                self.master.file_manager.log_engine.emit(info, LogName.Running)
                # excel的每一个sheet
                row_cont_o = []
                for profit_cost_multiple in profit_cost_multiple_ls:
                    row_o = []
                    for loss_cost_multiple in loss_cost_multiple_ls:
                        average_profit_multiple = (profit_probability*(profit_cost_multiple - 1) -
                                                   (1 - profit_probability)*(loss_cost_multiple + 1))
                        average_profit_multiple = round(average_profit_multiple, 4)
                        row_o.append(average_profit_multiple)
                    row_cont_o.append(row_o)
                sheet_name = f"正向概率{profit_probability}"
                columns = loss_cost_multiple_ls
                indices = profit_cost_multiple_ls
                sheet_df = pd.DataFrame(np.array(row_cont_o), columns=columns, index=indices)
                sheet_df.index.name = r"正向\反向倍数"
                sheet_df.to_excel(writer, sheet_name=sheet_name, index=True)
        info = f"运行结束，文件路径：{excel_path}"
        self.master.file_manager.log_engine.emit(info, LogName.FileAction)
        pass
